<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>商品分类</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片信息 -->
        <el-card>
            <!-- 添加商品分类按钮 -->
            <el-row>
                <el-col>
                    <el-button type="primary" @click="addClassify">添加分类</el-button>
                </el-col>
            </el-row>
            <!-- 商品分类表单 -->
            <tree-table class="treetable" :data="this.cateList" :columns="columns" :show-row-hover="false" :selection-type="false" :expand-type="false" show-index index-text="#" border>
                <!-- 是否有效 -->
                <template slot="isOk" slot-scope="scope">
                    <i class="el-icon-success" style="color:lightgreen" v-if="scope.row.cat_deleted === false"></i>
                    <i class="el-icon-error" style="color:red" v-else></i>
                </template>
                <!-- 排序 -->
                <template slot="sort" slot-scope="scope">
                    <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
                    <el-tag type="success" size="mini" v-else-if="scope.row.cat_level === 1">二级</el-tag>
                    <el-tag type="warning" size="mini" v-else>三级</el-tag>
                </template>
                <!-- 操作 -->
                <template slot="opt" slot-scope="scope">
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="editGoodesCate(scope.row)">编辑</el-button>
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteGoodesCate(scope.row)">删除</el-button>
                </template>
            </tree-table>
            <!-- 分页栏 -->
             <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="this.queryInfo.pagenum" :page-sizes="[3, 5, 10, 15]" :page-size="this.queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="this.totalpage">
            </el-pagination>
        </el-card>

        <!-- 添加分类对话框 -->
        <el-dialog title="添加分类" :visible.sync="addDialogVisible" width="50%" @close="emptyaAddFrom">
            <el-form :model="addFrom" :rules="addFormRules" ref="addFormRef" label-width="100px" status-icon>
                <el-form-item label="分类名称：" prop="cat_name">
                    <el-input v-model="addFrom.cat_name"></el-input>
                </el-form-item>
                <el-form-item label="父级分类：">
                     <el-cascader v-model="addParentsKeysId" :options="parentgcList" :props="configureInfo" @change="handleChange" clearable>
                     </el-cascader>
                </el-form-item>
            </el-form>
             <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addNewCate">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑商品分类 -->
        <el-dialog title="修改分类" :visible.sync="modifyCateDialogVisible" width="50%">
          <el-form :model="modifyCateInfo" status-icon :rules="modifyRules" ref="modifyRuleFormRef" label-width="100px">
            <el-form-item label="分类名称：" prop="cat_name">
               <el-input v-model="modifyCateInfo.cat_name" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="modifyCateDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="modifyNewClassify">确 定</el-button>
          </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
  data() {
    return {
      // 基础显示信息
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      // 表单列表
      cateList: [],
      // 数据总条数
      totalpage: 0,
      // 表头配置
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'isOk'
        },
        {
          label: '排序',
          type: 'template',
          template: 'sort'
        },
        {
          label: '操作',
          type: 'template',
          template: 'opt'
        }
      ],
      //   是否显示添加商品分类对话框
      addDialogVisible: false,
      // 添加商品分类对象
      addFrom: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0
      },
      // 添加商品分类表单验证
      addFormRules: {
        cat_name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
      },
      // 添加商品分类级联选择框数据
      parentgcList: [],
      // 添加父级Id
      addParentsKeysId: [],
      // 级联选择框配置信息
      configureInfo: {
        checkStrictly: true,
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 修改分类对话框显示与隐藏
      modifyCateDialogVisible: false,
      // 要修改的分类信息
      modifyCateInfo: {
        cat_id: '',
        cat_name: ''
      },
      // 修改商品分类表单验证
      modifyRules: {
        cat_name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    //   获取商品分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        return this.$message({
          showClose: true,
          message: '获取商品分类列表失败！',
          type: 'error'
        })
      }
      this.cateList = res.data.result
      this.totalpage = res.data.total
    },
    // 监听 pagesize 变化
    handleSizeChange(newPagesize) {
      this.queryInfo.pagesize = newPagesize
      this.getCateList()
    },
    // 监听 pagenum 变化
    handleCurrentChange(newPagenum) {
      this.queryInfo.pagenum = newPagenum
      this.getCateList()
    },
    // 点击添加分类
    addClassify() {
      this.getGoodsClassify()
      this.addDialogVisible = true
    },
    // 获取父级分类列表
    async getGoodsClassify() {
      const { data: res } = await this.$http.get('/categories', { params: { type: 2 } })
      if (res.meta.status !== 200) {
        return this.$message({
          showClose: true,
          message: '获取商品分类失败！',
          type: 'error'
        })
      }
      this.parentgcList = res.data
    },
    // 当级联选择框发生改变时
    handleChange() {
      // console.log(this.addParentsKeysId)
      // 如果 addParentsKeysId 数组中的 length 大于0，证明选中的父级分类
      // 反之，就说明没有选中任何父级分类
      if (this.addParentsKeysId.length > 0) {
        // 父级分类的Id
        this.addFrom.cat_pid = this.addParentsKeysId[this.addParentsKeysId.length - 1]
        // 为当前分类的等级赋值
        this.addFrom.cat_level = this.addParentsKeysId.length
      } else {
        // 父级分类的Id
        this.addFrom.cat_pid = 0
        // 为当前分类的等级赋值
        this.addForm.cat_level = 0
      }
    },
    // 点击确定添加新的商品分类
    addNewCate() {
      this.$refs.addFormRef.validate(async val => {
        if (!val) return
        const { data: res } = await this.$http.post('categories', this.addFrom)
        if (res.meta.status !== 201) {
          return this.$message({
            showClose: true,
            message: '添加分类失败！',
            type: 'error'
          })
        }

        this.$message.success('添加分类成功！')
        this.getCateList()
        this.addDialogVisible = false
      })
    },
    // 清空添加分类对话框
    emptyaAddFrom() {
      this.$refs.addFormRef.resetFields()
      this.addParentsKeysId = []
      this.addFrom.cat_level = 0
      this.addFrom.cat_pid = 0
    },
    // 编辑商品分类
    editGoodesCate(cateInfo) {
      this.modifyCateInfo.cat_id = cateInfo.cat_id
      this.modifyCateInfo.cat_name = cateInfo.cat_name
      this.modifyCateDialogVisible = true
    },
    // 点击确定修改商品分类
    async modifyNewClassify() {
      const { data: res } = await this.$http.put('/categories/' + this.modifyCateInfo.cat_id, { cat_name: this.modifyCateInfo.cat_name })
      if (res.meta.status !== 200) {
        return this.$message({
          showClose: true,
          message: '更新分类失败！',
          type: 'error'
        })
      }
      this.$message({
        showClose: true,
        message: '更新分类成功！',
        type: 'success'
      })
      this.getCateList()
      this.modifyCateInfo.cat_id = ''
      this.modifyCateInfo.cat_name = ''
      this.modifyCateDialogVisible = false
    },
    // 点击删除按钮，删除分类
    async deleteGoodesCate(deleteCateInfo) {
      const deleteInfo = await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (deleteInfo !== 'confirm') {
        return this.$message({
          showClose: true,
          message: '删除分类操作已取消！',
          type: 'info'
        })
      } else {
        const { data: res } = await this.$http.delete('categories/' + deleteCateInfo.cat_id)
        this.getCateList()
        this.$message({
          showClose: true,
          message: res.meta.msg,
          type: 'success'
        })
      }
    }
  }
}
</script>

<style lang="less" scoped>
.treetable{
    margin-top: 20px;
}
.el-pagination {
    margin-top: 20px;
}
.el-cascader{
  width: 100%;
}
</style>
